<template>
  <div class="container">
    <!-- <h1>注册界面</h1> -->
    <el-row class="row-md" justify="center">
      <el-col :span="7">
        <h1 id="title">EasyBrain</h1>
      </el-col>
    </el-row>
    <el-row class="row-md" justify="center">
      <el-col :span="7">
        <div class="form">
          <br />
          <el-row class="row-md" justify="start">
            <el-col :span="7" :offset="2">
              <el-tabs v-model="activeName" class="demo-tabs" @tab-click="tabChange">
                <el-tab-pane label="登录" name="first" index="/login"></el-tab-pane>
                <el-tab-pane label="注册" name="second" index="/register"></el-tab-pane>
              </el-tabs>
            </el-col>
          </el-row>
          <el-row class="row-md" justify="center">
            <el-col :span="20">
              <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="用户名" prop="name">
                  <el-input v-model="form.name" type="text" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="form.nickname" type="text" placeholder="请输入昵称" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" type="text" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="密码" prop="pwd">
                  <el-input v-model="form.pwd" type="password" placeholder="请输入密码" show-password />
                </el-form-item>
                <el-form-item label="重复密码" prop="repwd">
                  <el-input v-model="form.repwd" type="password" placeholder="请重复密码" show-password />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="onSubmit">注 册</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { useRoute, useRouter } from 'vue-router';
import { reactive, ref } from 'vue';
import { TabsPaneContext } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'
import { registerApi } from "@/utils/request"
import { Md5 } from 'ts-md5'


// interface formType {
//   name: string,
//   nickname: string,
//   email: string,
//   pwd: string,
//   repwd: string
// }
const ruleFormRef = ref<FormInstance>()
const form = reactive({
  name: "",
  nickname: "",
  email: "",
  pwd: "",
  repwd: ""
})

var checkEmail = (rule: any, value: any, cb: any) => {
  //验证邮箱的正则表达式
  const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  if (regEmail.test(value)) {
    //合法的邮箱
    return cb();
  }
  cb(new Error("请输入合法的邮箱"));
}
const validatePass2 = () => {
  return (rule: any, value: any, callback: any) => {
    if (value !== form.pwd && form.pwd !== '') {
      callback(new Error('两次输入密码不一致!'))
    } else {
      callback()
    }
  }
}
const validatePass1 = () => {
  return (rule: any, value: any, callback: any) => {
    if (
      value !== form.repwd &&
      form.repwd !== ''
    ) {
      callback(new Error('两次输入密码不一致!'))
    } else {
      callback()
    }
  }
}
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      validator: checkEmail,
      min: 9,
      max: 18,
      message: "邮箱格式错误",
      trigger: "blur",
    }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      min: 6,
      max: 18,
      message: '密码长度需要在6-18位之间',
      trigger: 'change'
    },
    {
      validator: validatePass1(),
      trigger: 'change'
    }
  ],
  repwd: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      min: 6,
      max: 18,
      message: '密码长度需要在6-18位之间',
      trigger: 'change'
    },
    {
      trigger: 'change',
      validator: validatePass2()
    }

  ]

})


const activeName: string = "second"
const routes = useRoute()
const router = useRouter()
const tabChange: any = (tab: TabsPaneContext, event: Event) => {
  if (tab.paneName == "first") {
    router.push({
      path: "/",
      name: "login"
    })
  }
  else if (tab.paneName == "second") {
    router.push({
      path: "/register",
      name: "register"
    })
  }
}
const ChangeLogin: any = () => {
  router.push({
    path: "/login",
    name: "login2"
  })
}
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  else
    try {
      await ruleFormRef.value.validate((isValid, invalidFields) => {
        console.log(isValid);
        console.log(invalidFields);
      });
      console.log(form.name);
      if(localStorage['name']===form.name)
      {
        alert("用户名已存在");//如果用户名已存在则无法注册
      }
      else if(form.name==='')
      {
        alert("用户名不能为空");
      }
      else{//将新用户信息存储到localStorage
        localStorage.setItem('name',form.name);
        localStorage.setItem('password',form.pwd);
        localStorage.setItem('email',form.email);
        localStorage.setItem('nickname',form.nickname);
        localStorage.setItem('s',"false");
        alert("注册成功");
      }
      //完成注册后跳转至登录页面
      router.push({
        path: "/login",
        name: "login2"
      })
    } catch (error) {
      throw new Error('表单验证失败？')
    }
    registerApi({
    "username": form.name,
    "nickname": form.nickname,
    "email": form.email,
    "password": Md5.hashStr(form.pwd) 
  }).then(res=>{
    console.log("注册信息",res)
  })
}


</script>


